package com.daoyuan.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class FileTest {
	public static void main(String[] args) throws Exception {
		System.out.println("Hello, Java!");
		
		/* FileHandler */
//		FileConveter(new File("/home/daoyuan/Desktop/XQA.html"), new File("/home/daoyuan/Desktop/XQA.log"));
		
		/* download pictures from file which contains urls */
//		BufferedReader br = new BufferedReader(new FileReader(new File("/home/daoyuan/Desktop/XQA.log")));
//		String rl = "";
//		while((rl=br.readLine())!=null) {
//			downloadFromUrl(rl, "/home/daoyuan/Desktop/pics/");
//		}
	}
	
	public static void FileConveter(File inFile, File outFile) {
		BufferedReader br;
		BufferedWriter bw;
		try {
			br = new BufferedReader(new FileReader(inFile));
			bw = new BufferedWriter(new FileWriter(outFile));
			
			String rl = "";
			while((rl=br.readLine())!=null) {
				if(rl.contains("4_img") && rl.contains("<dd>")) {
					System.out.println(rl.replaceFirst("		<dd>", "").replaceFirst("</dd>", ""));
					bw.append(rl.replaceFirst("		<dd>", "").replaceFirst("</dd>", ""));
					bw.newLine();
				}
			}
			
			bw.close();
			br.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void downloadFromUrl(String url, String dir) throws Exception {
		URL httpurl = new URL(url);
		String fileName = getFileNameFromUrl(url);
		System.out.println(fileName);
		
		URLConnection con = httpurl.openConnection();
		InputStream is = con.getInputStream();
		byte[] bs = new byte[1024];
		int len;
		OutputStream os = new FileOutputStream(new File(dir+fileName));
		
		while((len=is.read(bs))!=-1) {
			os.write(bs, 0, len);
		}
		
		os.close();
		is.close();
	}
	
	public static String getFileNameFromUrl(String url) {
		String name = new Long(System.currentTimeMillis()).toString()+".X";
		int index = url.lastIndexOf("/");
		if(index>0) {
			name = url.substring(index+1);
			if(name.trim().length()>0) {
				return name;
			}
		}
		return name;
	}
}
